﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Diagnostics;
using System.Text;
using WebApp.Comm;

namespace WebApp.Extensions
{
    internal static class ServiceCollectionExtension
    {
        public static IServiceCollection AddAuth(this IServiceCollection services, IConfiguration configuration)
        {
            // 设置验证方式为 Bearer Token
            // 你也可以添加 using Microsoft.AspNetCore.Authentication.JwtBearer;
            // 使用 JwtBearerDefaults.AuthenticationScheme 代替 字符串 "Bearer"
            services.AddAuthentication("Bearer")
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true,// 是否验证发布者
                            ValidateAudience = true,// 是否验证订阅者
                            ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,
                            ValidIssuer = configuration.GetValue<string>("JWT:Issuer"),
                            ValidAudience = configuration.GetValue<string>("JWT:Audience"),
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue<string>("JWT:Key"))),
                            RequireExpirationTime = true
                        };
                    });
            services.Configure<JwtOption>(configuration.GetSection("JWT"));
            return services;
        }
    }
}
